package com.shops.servlet.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {
	private static Properties prop = new Properties();

	static {
		InputStream is = null;
		try {
			is = JdbcUtil.class
					.getResourceAsStream("C:\\shops_start\\resources\\db.properties");
			prop.load(is);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static final ThreadLocal<Connection> t = new ThreadLocal<Connection>();

	public static Connection getConn() {
		Connection conn = t.get();
		try{
			if (conn == null) {
				String driver = prop.getProperty("mydriver");
				String url = prop.getProperty("myurl");
				String username = prop.getProperty("username");
				String pwd = prop.getProperty("pass");

				Class.forName(driver);
				conn = DriverManager.getConnection(url, username, pwd);

				t.set(conn);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return conn;
	}

	public static void release(ResultSet rs, Statement stm, Connection conn) {
		try{
			if (rs != null)
				rs.close();
			if (stm != null)
				stm.close();
			if (conn != null) {
				conn.close();
				t.remove();
			}
		}catch(Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) {
		Integer m = 0;
		System.out.println(m == null);
	}
}
